<?php

namespace tools;

class ModelProperty
{
    public function run()
    {
        $files = glob('application/component/*');

        if ($files) {
            foreach ($files as $file) {

                $model_files = glob($file . '/*Model.php');

                if ($model_files) {
                    foreach ($model_files as $file_path) {
                        $namespace = preg_replace(['/application/', '/\//', '/[\w]+\.php/'], ['app', '\\\\', ''], $file_path);
                        $namespace = trim($namespace, '\\');

                        $file_name = pathinfo($file_path, PATHINFO_FILENAME);

                        $table_name = preg_replace('/Model/', '', $file_name);

                        $result = tableColumns(transToUnderline($table_name));

                        $property = [];

                        if ($result) {
                            foreach ($result as $item) {
                                $property[] = [
                                    'type' => $item['Type'],
                                    'field' => $item['Field'],
                                ];
                            }
                        }

                        $template = appendModelClassProperty($property, $file_name, $namespace);

                        $file_content = file_get_contents($file_path);

                        if (preg_match('/@package|@property/', $file_content)) {
                            echo 'continue:' . $file_path . "\n";
                            continue;
                        }

                        $result = file_put_contents($file_path, preg_replace("/(class $file_name extends Model)/", $template . "\n\n" . '$1', $file_content));

                        if ($result) {
                            echo 'success:' . $file_path . "\n";
                        } else {
                            echo 'fail:' . $file_path . "\n";
                        }
                    }
                }


            }
        }

    }
}